package com.chenxin.transaction.service.impl;

import com.chenxin.transaction.dao.AccountInfoDao;
import com.chenxin.transaction.service.TccAccountInfoService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.dromara.hmily.core.concurrent.threadlocal.HmilyTransactionContextLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class TccLisiAccountInfoServiceImpl implements TccAccountInfoService {

    @Autowired
    private AccountInfoDao accountInfoDao;

    /**
     * 因为李四收到钱，而李四增加钱的操作不能写到try里，因为try会把钱写到数据库里，而一旦这个钱
     * 被其他用户消费了，就无法找回了，所以必须要等到comfirm确认
     * 一般confirm
     *
     * @param accountNo
     * @param amount
     */
    @Transactional
    @Hmily(confirmMethod = "confirmLs", cancelMethod = "rollbackLs")
    public void updateAccountBalance(String accountNo, Double amount) {
        //获取全局事务id
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("bank2 try begin 开始执行...xid:{}", transId);

//        if(accountInfoDao.addAccountBalance(accountNo, amount)>0){
//            log.info("李四单独价钱！！！");
//        }

    }

    /**
     * confirm方法
     * confirm幂等校验
     * 正式增加金额
     *
     * @param accountNo
     * @param amount
     */
    @Transactional
    public void confirmLs(String accountNo, Double amount) {
        //获取全局事务id
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("lisi confirm begin 开始执行...xid:{}", transId);
        if (accountInfoDao.isExistConfirm(transId) > 0) {
            log.info("lisi confirm 已经执行，无需重复执行...xid:{}", transId);
            return;
        }
        //增加金额
        accountInfoDao.addAccountBalance(accountNo, amount);
        //增加一条confirm日志，用于幂等
        accountInfoDao.addConfirm(transId);
        log.info("lisi confirm end 结束执行...xid:{}", transId);
    }


    /**
     * @param accountNo
     * @param amount
     */
    @Transactional
    public void rollbackLs(String accountNo, Double amount) {
        //获取全局事务id
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("lisi cancel begin 开始执行...xid:{}", transId);

    }
}
